/**
 * 
 */
package com.tuttle.twitterbot.util

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.GetMethod
import org.apache.commons.httpclient.auth.*
import org.apache.commons.httpclient.methods.PostMethod
/**
 * @author elishaezeugoh
 *
 */
public class TwitterClient {

	def userName
	def password
	def public static String USER_MENTIONS_URL = "http://twitter.com/statuses/mentions.xml"
	def public static String USER_UPDATE_URL = "http://twitter.com/statuses/update.xml"
	def public static String USER_DESTROY_URL = "http://twitter.com/statuses/destroy.xml"
	def private static String AUTH_DOMAIN = "twitter.com"
	def private static String AUTH_REALM = "Twitter API"
	def private static int AUTH_PORT = 80	
	
	TwitterClient() {
		
	}
	
	TwitterClient(userName,password) {
		this.userName = userName
		this.password = password
	}
	
	def setUserName(uname) {
		userName = uname
	}
	def setPassword(pword) {
		password = pword
	}
	
	def private updateStatus( String update) {


			def client = new HttpClient()
			configureClientAuthentication(client)		
			def post = new PostMethod(USER_UPDATE_URL)
			post.setDoAuthentication(true)
			post.setRequestHeader("Accept", "text/xml")
			post.addParameter("status",update);
			def result = client.executeMethod(post)
			def text = post.getResponseBodyAsString()
			def status = new XmlSlurper().parseText(text)
			def statusItem = processStatus(status)
			post.releaseConnection()
			return statusItem
	}
	
	def deleteStatus( String id) {


	def client = new HttpClient()
	configureClientAuthentication(client)		
	def post = new PostMethod(USER_DESTROY_URL)
	post.setDoAuthentication(true)
	post.setRequestHeader("Accept", "text/xml")
	post.addParameter("id",id);
	def result = client.executeMethod(post)
	def text = post.getResponseBodyAsString()
	def status = new XmlSlurper().parseText(text)
	def statusItem = processStatus(status)
	post.releaseConnection()
	return statusItem
}	
	def getMostRecentMentions() {


			def client = new HttpClient()
			configureClientAuthentication(client)		
			def get = new GetMethod(USER_MENTIONS_URL)
			get.setDoAuthentication(true)
			get.setRequestHeader("Accept", "text/xml")
			def result = client.executeMethod(get)
			def text = get.getResponseBodyAsString()
			def statuses = new XmlSlurper().parseText(text)
			def statusList = processStatusesList(statuses)
			get.releaseConnection()
			return statusList
	}

	def getMostRecentMentionsSince(String lastStatusId) {


			def url = "${USER_MENTIONS_URL}?since_id=${lastStatusId}"
			def client = new HttpClient()
			configureClientAuthentication(client)
			def get = new GetMethod(url)
			get.setDoAuthentication(true)
			get.setRequestHeader("Accept", "text/xml")
			def result = client.executeMethod(get)
			def text = get.getResponseBodyAsString()
			def statuses = new XmlSlurper().parseText(text)
			def statusList = processStatusesList(statuses)
			get.releaseConnection()
			return statusList
	}	
	
	def private processStatusesList(statuses) {
		def statusList = []
		statuses.status.each {
			println it.id.text()
			statusList.add(["id":"${it.id.text()}","text":"${it.text.text()}","twitterId":"${it.user.id.text()}",
			                "fullName":"${it.user.name.text()}","screenName":"${it.user.'screen_name'.text()}"])
		}	
		println statusList
		return statusList
	}

	
	def private processStatus(status) {
		def statusItem = 
			["id":"${status.id.text()}","text":"${status.text.text()}","twitterId":"${status.user.id.text()}",
			                "fullName":"${status.user.name.text()}","screenName":"${status.user.'screen_name'.text()}"]
	
		println statusItem
		return statusItem
	}	
	
	def private configureClientAuthentication(client) {
		if (client != null) {
			println "Credentials ${userName} ${password}"
			if (userName == null || userName.length() < 1 ||
				password == null || password.length() < 1) {
				throw new RuntimeException("Credentials must be supplied to twitter client")
			}
			
			client.getState().setCredentials(
		            new AuthScope(AUTH_DOMAIN, AUTH_PORT, AUTH_REALM),
		            new UsernamePasswordCredentials(userName, password)
		    )	
		}
	}
}
